package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.UUID;

/**
 * ClassName: CommonController
 * Package: com.sky.controller.admin
 * Description:通用接口
 *
 * @Author: Zhang Peiyuan
 * @Create: 2024-12-18-16:44
 * @Version: v1.0
 */
@RestController
@RequestMapping("/admin/common")
public class CommonController {
    @Resource
    public AliOssUtil aliOssUtil;

    /**
     * 返回上传文件的 oss 地址
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(@RequestParam(value="file") MultipartFile file) {
        // 获得原始文件名
        String originalFilename = file.getOriginalFilename();
        // 保证文件名唯一(uuid + .后缀)
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
        // 返回上传文件的 oss 地址
        try {
            return Result.success(aliOssUtil.upload(file.getBytes(), fileName));
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(MessageConstant.UPLOAD_FAILED);
        }
    }
}
